package com.csun.nusing.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.csun.nusing.R;
import com.csun.nusing.bean.UrlBean;
import com.csun.nusing.bean.jsonbean.FollowDeviceSearchBloodOxyJsonBean;
import com.csun.nusing.bean.jsonbean.FollowDeviceSearchBloodOxyJsonBean.DeviceSearchBloodOxyDataBean;
import com.csun.nusing.bean.jsonbean.FollowDeviceSearchBloodOxyJsonBean.DeviceSearchBloodOxyDataBean.BoxvygenListBean;
import com.csun.nusing.presenter.CommonPresenter;
import com.csun.nusing.presenter.inter.IBase;
import com.csun.nusing.ui.BaseActivity;
import com.csun.nusing.ui.myview.DoubleTimerPickerDialog;
import com.csun.nusing.util.SPUtils;
import com.csun.nusing.util.ToastUtil;
import com.csun.ttfutil.TTFSdk;
import com.google.gson.Gson;
import com.home.administrator.okhttplibrary.IOkTaskCallback;
import com.home.administrator.okhttplibrary.OkHttpTask;
import com.home.administrator.okhttplibrary.OkHttpTask.OkHttpTaskBuidler.OkType;
import com.linktop.whealthService.HealthApi;
import com.linktop.whealthService.HealthApi.BleCallBack;
import com.linktop.whealthService.HealthApi.EcgCallBack;
import com.linktop.whealthService.HealthApi.HealthApiCallBack;
import com.linktop.whealthService.OnBLEService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * 血氧测试的主界面 ClassName: BloodPressTestActivity
 * 
 * @Description: TODO
 * @author fzq
 * @date 2017-10-25
 */
public class BloodOxyMainActivity extends BaseActivity<CommonPresenter>
		implements IBase {

	// 控件
	private LineChartView line_chart;
	private LinearLayout picll;
	private LinearLayout datall;
	private ListView datelv;
	private TextView historydatetv;
	private TextView pictv;
	private TextView datetv;
	private ImageView measure_iv;
	private TextView choosetv;
	private TextView timepick_tv;

	//
	private List<String> Xdate = new ArrayList<String>();
	private List<Float> score = new ArrayList<Float>();

	private List<PointValue> mPointValues = new ArrayList<PointValue>();
	private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();
	public Intent intent;
	private Calendar calendar;
	private int year;
	private int month;
	private int day;
	private int hour = 10;
	private int min = 25;
	private int mendhour = 10;
	private int mendMin = 25;
	private String olderId;
	private String authorization;
	protected FollowDeviceSearchBloodOxyJsonBean devicesearchbloodoxyJsonBean;
	private List<BoxvygenListBean> datalist;
	private TextView statetv;
	private TextView suggesttv;
	private TextView bpmaxtv;
	private TextView bpmintv;
	protected String startdaytime = "";
	protected String enddaytime = "";
	private RelativeLayout navrl;
	private boolean isFamily;
	private int nowmonth;
	private int nowyear;
	private int nowday;
	private boolean bleOn;
	private String deviceMacAddress;
	private HealthApi mHealthApi;
	private static final int REQUEST_BLUETOOTH_DEVICE = 0;// 蓝牙连接
	private static final int REQUEST_OPEN_BT = 2;

	@Override
	public int getContentViewId() {
		return R.layout.activity_blood_oxy;
	}

	@Override
	public void initSubViews(View view) {
		super.initSubViews(view);
		/**
		 * find控件
		 */
		initView();
	}

	@Override
	public void initData() {
		super.initData();
		initDate();

	}

	/**
	 * 獲取數據,展示數據 图表展示
	 * 
	 * @Description:
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	private void initDate() {
		olderId = getIntent().getStringExtra("olderId");
		navrl = findViewById(R.id.nav_rl);
		isFamily = getIntent().getBooleanExtra("isFamily", false);
		bleOn = getIntent().getBooleanExtra("bleOn", false);
		deviceMacAddress = getIntent().getStringExtra("deviceMacAddress");
		if (isFamily) {
			navrl.setBackgroundResource(R.drawable.main_whiteyello_color_shape);
		}
		// showlv();//展示lv的数据
		calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH) + 1;
		day = calendar.get(Calendar.DAY_OF_MONTH);
		nowyear = year;
		nowmonth = month;
		nowday = day;
		timepick_tv.setText("1月" + "1日-" + nowmonth + getString(R.string.month) + nowday + getString(R.string.day));
		requestData();
		getAxisXLables();// 获取x轴的标注
		getAxisPoints();// 获取坐标点
		initLineChart();// 初始化
		mHealthApi = new HealthApi();
		mHealthApi.init(getApplicationContext(), new healthapicallback(),
				mbpHandler, mbtHandler, moxHandler, mbsHandler,
				new ecgcallback());
		mHealthApi.setBleCallBack(new blecallback());

	}

	private class healthapicallback implements HealthApiCallBack {
		@Override
		public void healthCallBack(int type, Object data) {
		}
	}

	private class ecgcallback implements EcgCallBack {
		@Override
		public void onReceive(int[] data) {
		}
	}

	private Handler mbtHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler moxHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler mbpHandler = new Handler() {
		public void handleMessage(Message msg) {
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler mbsHandler = new Handler() {
		public void handleMessage(Message msg) {
		}
	};
	private Timer batteryQueryTimer;

	private class blecallback implements BleCallBack {
		@Override
		public void bleCallBack(int type, Object data) {
			if (type == HealthApi.BLE_STATUS) {
				setBleUiState((Integer) data);
			}
		}
	}

	private void modual_init() {
		mHealthApi.ecgQuery();
		mHealthApi.bsQuery();
		mHealthApi.batteryQuery();

		if (batteryQueryTimer == null)
			batteryQueryTimer = new Timer();
		batteryQueryTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				mHealthApi.batteryQuery();
			}
		}, 300000, 300000);
	}

	private void setBleUiState(int mState) {
		switch (mState) {
		case OnBLEService.BLE_CONNECTED:
			break;
		case OnBLEService.BLE_DISCONNECTED:
			break;
		case OnBLEService.BLE_NOTIFICATION_ENABLED:
			modual_init();
			break;
		case OnBLEService.BLE_NOTIFICATION_NOTENABLED:
			break;
		default:
			break;
		}
	}

	/**
	 * 搜索蓝牙设备
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	public void searchDevice() {
		if (BluetoothAdapter.getDefaultAdapter().isEnabled()) {
			if (!bleOn) {// mState != BLE_DISCONNECTED
				Intent intent = new Intent(BloodOxyMainActivity.this,
						FollowDeviceSearchActivity.class);
				if (deviceMacAddress != null && deviceMacAddress.length() > 4) {
				} else {
					ToastUtil.showMessage(getApplicationContext(),
							"请选择搜索到的随访仪设备");
				}
				intent.putExtra("deviceMacAddress", "" + deviceMacAddress);
				intent.putExtra("isFamily", isFamily);
				startActivityForResult(intent, REQUEST_BLUETOOTH_DEVICE);
			} else {
				// 断开设备蓝牙
				mHealthApi.bleDisconnect();
				bleOn = false;
				ToastUtil.showMessage(this, R.string.ble_is_un_relative);
			}
		} else {
			enableBluetooth();
		}
	}

	/**
	 * 打开手机蓝牙
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	private void enableBluetooth() {
		BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
		if (bta == null) {
			Toast.makeText(this, R.string.not_support_ble, Toast.LENGTH_SHORT).show();
		} else {
			if (!bta.isEnabled()) {
				startActivityForResult(new Intent(
						"android.bluetooth.adapter.action.REQUEST_ENABLE"),
						REQUEST_OPEN_BT);
			}
		}
	}

	/**
	 * 请求数据
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-31
	 */
	private void requestData() {
		/**
		 * 请求数据
		 */
		authorization = (String) SPUtils.get(this, "authorization", "");
		Map<String, String> param = new HashMap<String, String>();
		param.put("oldmanId", "" + olderId);
		OkHttpTask.newInstance(this).post(param, OkType.form)
				.addHeader("authorization", authorization)
				.enqueue(new IOkTaskCallback() {
					@Override
					public void onSuccess(String result) {
						if (result != null) {
							Gson gson = new Gson();
							devicesearchbloodoxyJsonBean = gson.fromJson(
									result,
									FollowDeviceSearchBloodOxyJsonBean.class);
							if (devicesearchbloodoxyJsonBean != null
									&& devicesearchbloodoxyJsonBean.getData() != null) {
								controlData(devicesearchbloodoxyJsonBean
										.getData());
							}
						}
					}
				}).start(UrlBean.SEARCHBLEBOXYGENRELATIONURL);
	}

	protected void controlData(DeviceSearchBloodOxyDataBean data) {
		bpmaxtv.setText("" + (int) data.getMax() + "%");
		bpmintv.setText("" + (int) data.getMin() + "%");
		statetv.setText("" + data.getStatus());
		suggesttv.setText("" + data.getSuggest());
		datalist = data.getBoxvygenList();
		for (int i = 0; i < datalist.size(); i++) {
			SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
			Date date = new Date(datalist.get(i).getCreateTime());
			Xdate.add(sdf.format(date));
			score.add((float) datalist.get(i).getBoxygen());
		}
		getAxisXLables();// 获取x轴的标注
		getAxisPoints();// 获取坐标点
		initLineChart();// 初始化
	}

	/**
	 * 点击事件监听
	 * 
	 * @Description:
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-11
	 */
	private void initView() {
		bpmaxtv = findViewById(R.id.bloodpresstest_bpmax_tv);
		bpmintv = findViewById(R.id.bloodpresstest_bpmin_tv);
		statetv = findViewById(R.id.bloooxytest_state_tv);
		suggesttv = findViewById(R.id.bloodoxytest_suggest_tv);

		measure_iv = findViewById(R.id.bloodoxy_main_measure_iv);
		line_chart = findViewById(R.id.bloodoxy_main_line_chart);
		picll = findViewById(R.id.bloodoxy_main_pic_ll);
		datall = findViewById(R.id.bloodoxy_main_data_ll);
		datelv = findViewById(R.id.bloodoxy_main_date_lv);
		historydatetv = findViewById(R.id.bloodoxy_main_historydata_tv);
		pictv = findViewById(R.id.bloodoxy_main_pic_tv);
		choosetv = findViewById(R.id.bloodoxy_main_time_choose_tv);
		datetv = findViewById(R.id.bloodoxy_main_date_tv);
		timepick_tv = findViewById(R.id.bloodoxy_main_timepick_tv);
		measure_iv.setOnClickListener(new click());
		historydatetv.setOnClickListener(new click());
		pictv.setOnClickListener(new click());
		datetv.setOnClickListener(new click());
		choosetv.setOnClickListener(new click());
		timepick_tv.setOnClickListener(new click());
	}

	/**
	 * 初始化LineChart的一些设置
	 * 
	 * @Description: chart设置
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-10
	 */
	private void initLineChart() {
		Line line = new Line(mPointValues);
		line.setColor(Color.WHITE); // 折线的颜色
		List<Line> lines = new ArrayList<Line>();
		line.setShape(ValueShape.CIRCLE);// 折线图上每个数据点的形状 这里是圆形 （有三种
											// ：ValueShape.SQUARE
											// ValueShape.CIRCLE
											// ValueShape.SQUARE）
		line.setCubic(false);// 曲线是否平滑
		line.setStrokeWidth(2);// 线条的粗细，默认是3
		line.setFilled(false);// 是否填充曲线的面积
		line.setHasLabels(true);// 曲线的数据坐标是否加上备注
		// line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
		line.setHasLines(true);// 是否用直线显示。如果为false 则没有曲线只有点显示
		line.setHasPoints(true);// 是否显示圆点 如果为false 则没有原点只有点显示
		lines.add(line);
		LineChartData data = new LineChartData();
		data.setLines(lines);

		// 坐标轴
		Axis axisX = new Axis(); // X轴
		axisX.setHasTiltedLabels(false); // X轴下面坐标轴字体是斜的显示还是直的，true是斜的显示
		axisX.setTextColor(Color.WHITE); // 设置字体颜色
		// axisX.setTextColor(Color.parseColor("#D6D6D9"));//灰色
		// 坐标轴颜色
		axisX.setLineColor(Color.TRANSPARENT);
		// axisX.setName("未来几天的天气"); //表格名称
		axisX.setTextSize(10);// 设置字体大小
		axisX.setMaxLabelChars(7); // 最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisValues.length
		axisX.setValues(mAxisXValues); // 填充X轴的坐标名称
		data.setAxisXBottom(axisX); // x 轴在底部
		// data.setAxisXTop(axisX); //x 轴在顶部
		axisX.setHasLines(true); // x 轴分割线

		Axis axisY = new Axis(); // Y轴
		axisY.setName("");// y轴标注
		axisY.setTextSize(11);// 设置字体大小
		data.setAxisYLeft(axisY); // Y轴设置在左边
		axisY.setLineColor(Color.TRANSPARENT);
		axisY.setTextColor(Color.WHITE);
		// data.setAxisYRight(axisY); //y轴设置在右边
		// 设置行为属性，支持缩放、滑动以及平移
		line_chart.setInteractive(true);
		// 设置能否缩放
		line_chart.setZoomEnabled(true);
		line_chart.setZoomType(ZoomType.HORIZONTAL); // 缩放类型，水平
		line_chart.setMaxZoom((float) 3);// 缩放比例
		line_chart.setLineChartData(data);
		line_chart.setVisibility(View.VISIBLE);
		/**
		 * 注：下面的7，10只是代表一个数字去类比而已
		 * 尼玛搞的老子好辛苦！！！见（http://forum.xda-developers.com/tools
		 * /programming/library-hellocharts-charting-library-t2904456/page2）;
		 * 下面几句可以设置X轴数据的显示个数
		 * （x轴0-7个数据），当数据点个数小于（29）的时候，缩小到极致hellochart默认的是所有显示。当数据点个数大于（29）的时候，
		 * 若不设置axisX.setMaxLabelChars(int count)这句话,则会自动适配X轴所能显示的尽量合适的数据个数。
		 * 若设置axisX.setMaxLabelChars(int count)这句话, 33个数据点测试，若
		 * axisX.setMaxLabelChars(10);里面的10大于v.right= 7; 里面的7，则
		 * 刚开始X轴显示7条数据，然后缩放的时候X轴的个数会保证大于7小于10 若小于v.right=
		 * 7;中的7,反正我感觉是这两句都好像失效了的样子 - -! 并且Y轴是根据数据的大小自动设置Y轴上限 若这儿不设置 v.right= 7;
		 * 这句话，则图表刚开始就会尽可能的显示所有数据，交互性太差
		 */
		Viewport v = new Viewport(line_chart.getMaximumViewport());
		v.left = 0;
		// 设置当前显示多少数据
		v.right = 8;
		line_chart.setCurrentViewport(v);
	}

	/**
	 * X 轴的显示
	 */
	private void getAxisXLables() {
		for (int i = 0; i < Xdate.size(); i++) {
			mAxisXValues.add(new AxisValue(i).setLabel(Xdate.get(i)));
		}
	}

	/**
	 * 图表的每个点的显示
	 */
	private void getAxisPoints() {
		for (int i = 0; i < score.size(); i++) {
			mPointValues.add(new PointValue(i, score.get(i)));
		}
	}

	/**
	 * 点击事件处理 ClassName: click
	 * 
	 * @Description: TODO
	 * @author fzq
	 * @date 2017-10-10
	 */
	private class click implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.bloodoxy_main_measure_iv:
				if (bleOn) {
					intent = new Intent(BloodOxyMainActivity.this,
							BloodOxyMessureActivity.class);
					intent.putExtra("olderId", olderId);
					intent.putExtra("isFamily", isFamily);
					startActivityForResult(intent, 0x33);
				} else {
					searchDevice();
				}
				break;
			case R.id.bloodoxy_main_historydata_tv:
				// 跳转温度历史记录界面
				intent = new Intent(BloodOxyMainActivity.this,
						BloodOxyHistoryActivity.class);
				intent.putExtra("olderId", olderId);
				intent.putExtra("isFamily", isFamily);
				startActivity(intent);
				break;
			case R.id.bloodoxy_main_pic_tv:
				picll.setVisibility(View.VISIBLE);
				datall.setVisibility(View.GONE);

				break;
			case R.id.bloodoxy_main_date_tv:
				picll.setVisibility(View.GONE);
				datall.setVisibility(View.VISIBLE);

				break;
			case R.id.bloodoxy_main_time_choose_tv:
				chooseTime();
				break;
			case R.id.bloodoxy_main_timepick_tv:
				chooseDay();
				break;
			}
		}
	}

	/**
	 * 筛选时间
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-11
	 */
	public void chooseTime() {
		new DoubleTimerPickerDialog(this,
				android.R.style.Theme_DeviceDefault_Light_Dialog,
				new DoubleTimerPickerDialog.OnDateSetListener() {

					@Override
					public void onDateSet(TimePicker startDatePicker,
							int starthour, int startMin,
							TimePicker endDatePicker, int endhour, int endMin) {
						hour = starthour;
						min = startMin;
						mendhour = endhour;
						mendMin = endMin;
						if (mendhour < hour) {
							mendhour = hour;
						}
						startdaytime = year + "-" + (month + 1) + "-" + day
								+ " " + hour + ":" + min + ":00";
						enddaytime = nowyear + "-" + nowmonth + "-" + nowday
								+ " " + mendhour + ":" + mendMin + ":00";
						choosetv.setText(getString(R.string.timess) + starthour + getString(R.string.time)+"-" + endhour
								+ getString(R.string.time));
						refreashData();
					}
				}, hour, min, mendhour, mendMin).show();
	}

	/**
	 * 选择日期
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-11
	 */
	private void chooseDay() {

		DatePickerDialog datePickerDialog = new DatePickerDialog(this,
				AlertDialog.THEME_HOLO_LIGHT, new OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						/**
						 * 保存设置的时间
						 */
						month = monthOfYear;
						day = dayOfMonth;
						String textString = String.format("%d月%d日",
								monthOfYear + 1, dayOfMonth);
						timepick_tv.setText(textString + "-" + nowmonth + getString(R.string.month)
								+ nowday + getString(R.string.day));
						// 2017-10-30 10:30:00
						startdaytime = year + "-" + (monthOfYear + 1) + "-"
								+ dayOfMonth + " " + hour + ":" + min + ":00";
						enddaytime = nowyear + "-" + nowmonth + "-" + nowday
								+ " " + mendhour + ":" + mendMin + ":00";
						// 刷新数据
						refreashData();
					}
				}, year, month, day);

		datePickerDialog.setCancelable(true);
		DatePicker dp = datePickerDialog.getDatePicker();
		dp.setMaxDate(calendar.getTimeInMillis());
		datePickerDialog.show();

	}

	/**
	 * 刷新数据
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-10-11
	 */
	private void refreashData() {
		/**
		 * 获取血压数据
		 */
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("oldmanId", olderId);
		param.put("startTime", startdaytime);
		param.put("endTime", enddaytime);
		OkHttpTask.newInstance(this).post(param, OkType.form)
				.addHeader("authorization", authorization)
				.enqueue(new IOkTaskCallback() {
					@Override
					public void onSuccess(String result) {
						if (result != null) {
							Gson gson = new Gson();
							devicesearchbloodoxyJsonBean = gson.fromJson(
									result,
									FollowDeviceSearchBloodOxyJsonBean.class);
							if (devicesearchbloodoxyJsonBean != null
									&& devicesearchbloodoxyJsonBean.getData() != null) {
								// 删除表
								deleteData();
								controlData(devicesearchbloodoxyJsonBean
										.getData());
							}
						}
					}
				}).start(UrlBean.SEARCHBLEBOXYGENRELATIONURL);

	}

	protected void deleteData() {
		Xdate = new ArrayList<String>();
		score = new ArrayList<Float>();
		mPointValues = new ArrayList<PointValue>();
		mAxisXValues = new ArrayList<AxisValue>();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mHealthApi != null)
			if (batteryQueryTimer != null)
				batteryQueryTimer.cancel();
		batteryQueryTimer = null;
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		refreashData();
		switch (requestCode) {
		case REQUEST_BLUETOOTH_DEVICE:
			if (resultCode == RESULT_OK) {
				String strAddress = data.getExtras().getString(
						BluetoothDevice.EXTRA_DEVICE);
				bleOn = true;
				
				if (!mHealthApi.bleConnect(strAddress)) {
					Log.e("fzq", "connect error");
					bleOn = false;
					// finish();
				}else{
					TTFSdk.speak(mSpeechSynthesizer,getString(R.string.follow_is_relative));
					intent = new Intent(BloodOxyMainActivity.this,
							BloodOxyMessureActivity.class);
					intent.putExtra("olderId", olderId);
					intent.putExtra("isFamily", isFamily);
					startActivityForResult(intent, 0x33);
				}
			} else {
				// bluetoothIv.setImageResource(R.drawable.bluetooth);
			}
			break;

		case REQUEST_OPEN_BT:
			if (resultCode == RESULT_OK) {
			} else {
			}
			break;

		}
	}
	
	
	/**
	 * 对back键的点击做判断，如果按back键，默认退回到主页面
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent();
			intent.putExtra("bleOn", bleOn);
			setResult(0x22, intent);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	//监听返回键
	public void OnBACK(View view){
		Intent intent = new Intent();
		intent.putExtra("bleOn", bleOn);
		setResult(0x22, intent);
		finish();
	}
    

}